package com.slfx.qrcode.util;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.util.Hashtable;

public class QRCodeUtil {

    private static final String CHARSET = "utf-8";

    // 二维码尺寸
    private static final int QRCODE_SIZE = 300;

    /**
     * 根据内容创建二维码
     * @param content
     * @return
     */
    public static BufferedImage createImage(String content) {
        Hashtable<EncodeHintType, Object> hints = new Hashtable();
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        hints.put(EncodeHintType.CHARACTER_SET, CHARSET);
        hints.put(EncodeHintType.MARGIN, 1);
        BitMatrix bitMatrix = null;
        try {
            bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, QRCODE_SIZE, QRCODE_SIZE,
                    hints);
        } catch (WriterException e) {
            e.printStackTrace();
        }
        int width = bitMatrix.getWidth();
        int height = bitMatrix.getHeight();
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
            }
        }
        return image;
    }

    // LOGO宽度
    private static final int LOGO_WIDTH = 80;
    // LOGO高度
    private static final int LOGO_HEIGHT = 80;
    /**
     * 插入LOGO
     *
     * @param source       二维码图片
     * @param logoPath     LOGO图片地址
     * @param needCompress 是否压缩
     * @throws Exception
     */
    public static void insertImage(BufferedImage source, InputStream logoPath, boolean needCompress)  {
        Image src = null;
        try {
            src = ImageIO.read(logoPath);
        } catch (IOException e) {
            e.printStackTrace();
        }
        int width = src.getWidth(null);
        int height = src.getHeight(null);
        if (needCompress) {
            // 压缩LOGO
            if (width > LOGO_WIDTH) {
                width = LOGO_WIDTH;
            }
            if (height > LOGO_HEIGHT) {
                height = LOGO_HEIGHT;
            }
            Image image = src.getScaledInstance(width, height, Image.SCALE_SMOOTH);
            BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            Graphics g = tag.getGraphics();
            // 绘制缩小后的图
            g.drawImage(image, 0, 0, null);
            g.dispose();
            src = image;
        }
        // 插入LOGO
        Graphics2D graph = source.createGraphics();
        int x = (QRCODE_SIZE - width) / 2;
        int y = (QRCODE_SIZE - height) / 2;
        graph.drawImage(src, x, y, width, height, null);
        Shape shape = new RoundRectangle2D.Float(x, y, width, width, 12, 12);
        graph.setStroke(new BasicStroke(3f));
        graph.draw(shape);
        graph.dispose();
    }


    // LOGO宽度
    private static final int QRCODE_WIDTH = 250;
    // LOGO高度
    private static final int QRCODE_HEIGHT = 250;

    private static final int IMAGE_HEIGHT = 300;
    private static final int DEFAULT_FONT_SIZE = 15;
    private static final int TEXT_DEFAULT_HEIGHT = 25;
    private static final int TEMP_PARAM = 15;

    /**
     * 给二维码下方添加说明文字
     *
     * @param image 原二维码
     * @param topText  顶部说明文字
     * @param downText 底部说明文字
     * @return 带说明文字的二维码
     */
    public static BufferedImage addNote(BufferedImage image, String topText, String downText) {
        Image src = image.getScaledInstance(QRCODE_WIDTH, QRCODE_HEIGHT, Image.SCALE_DEFAULT);
        BufferedImage tag = new BufferedImage(QRCODE_WIDTH, IMAGE_HEIGHT, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = tag.createGraphics();//设置文字
        g2.setColor(Color.BLACK);
        g2.setBackground(Color.WHITE);
        g2.clearRect(0,0,QRCODE_WIDTH, IMAGE_HEIGHT);
        //设置顶部文本并计算坐标
        // 保证操作系统包含“宋体”字体，如果没有上传字体至JAVA_HOME/jre/lib/fonts下
        FontMetrics fm = getFontByWidth(new Font("宋体", Font.PLAIN, DEFAULT_FONT_SIZE), topText, g2);
        //文字的宽度
        int fontWidth = fm.stringWidth(topText);
        //文字高度
        int fontHeight = fm.getHeight();
        /**
         * 顶部添加文字并居中
         */
        g2.drawString(topText, (QRCODE_WIDTH - fontWidth) / 2,  (TEXT_DEFAULT_HEIGHT - fontHeight) / 2 + fm.getFont().getSize());
        /**
         * 绘制二维码
         */
        g2.drawImage(src, 0, TEXT_DEFAULT_HEIGHT, null);
        // 设置底部文字字体并计算坐标
        // 保证操作系统包含“宋体”字体，如果没有上传字体至JAVA_HOME/jre/lib/fonts下
        fm = getFontByWidth(new Font("宋体", Font.PLAIN, DEFAULT_FONT_SIZE), downText, g2);
        //文字的宽度
        fontWidth = fm.stringWidth(downText);
        //文字高度
        fontHeight = fm.getHeight();
        /**
         * 添加底部文字
         */
        g2.drawString(downText, (QRCODE_WIDTH - fontWidth) / 2,  QRCODE_HEIGHT + TEXT_DEFAULT_HEIGHT+(TEXT_DEFAULT_HEIGHT - fontHeight) / 2 + fm.getFont().getSize());
        g2.dispose();
        image = tag;
        image.flush();
        return image;
    }

    /**
     * 根据文字长度改变文字大小
     *
     * @param font 默认字体
     * @param note 文字内容
     * @param g2 图像画布
     * @return 处理后的字体封装
     */
    private static FontMetrics getFontByWidth(Font font, String note, Graphics2D g2) {
        FontMetrics fm = g2.getFontMetrics(font);
        int textWidth = fm.stringWidth(note);//文字的宽度
        if (textWidth > QRCODE_WIDTH) {
            int fontSize = (int) ((TEMP_PARAM / textWidth) * font.getSize());
            font = new Font(font.getName(), font.getStyle(), fontSize);
        }
        g2.setFont(font);
        return g2.getFontMetrics(font);
    }

    /**
     * 给二维码左边添加说明文字
     *
     * @param image 原二维码
     * @param leftText  左边说明文字
     * @return 带说明文字的二维码
     */
    public static BufferedImage addNote(BufferedImage image, String leftText) {
        Image src = image.getScaledInstance(QRCODE_WIDTH, QRCODE_HEIGHT, Image.SCALE_DEFAULT);
//        BufferedImage tag = new BufferedImage(QRCODE_WIDTH, IMAGE_HEIGHT, BufferedImage.TYPE_INT_RGB);
        BufferedImage tag = new BufferedImage(IMAGE_HEIGHT,QRCODE_WIDTH, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = tag.createGraphics();//设置文字
        g2.setColor(Color.BLACK);
        g2.setBackground(Color.WHITE);
//        g2.clearRect(0,0,QRCODE_WIDTH,IMAGE_HEIGHT);
        g2.clearRect(0,0,IMAGE_HEIGHT,QRCODE_WIDTH);
        //设置顶部文本并计算坐标
        // 保证操作系统包含“宋体”字体，如果没有上传字体至JAVA_HOME/jre/lib/fonts下
        FontMetrics fm = getFontByWidth(new Font("宋体", Font.PLAIN, DEFAULT_FONT_SIZE), leftText, g2);
        //文字的宽度
        int fontWidth = fm.stringWidth(leftText);
        //文字高度
        int fontHeight = fm.getHeight();
        /**
         * 顶部添加文字并居中
         */
        g2.drawString(leftText, (TEXT_DEFAULT_HEIGHT - fontHeight) / 2 + fm.getFont().getSize(),(QRCODE_WIDTH - fontWidth) / 2);
        /**
         * 绘制二维码
         */
        g2.drawImage(src, 0, TEXT_DEFAULT_HEIGHT, null);
        g2.dispose();
        image = tag;
        image.flush();
        return image;
    }
}